#!/usr/bin/env python

import wsgiref.handlers

import time
import xml.dom.minidom
from douban import Constants
from douban import oAuth
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import urlfetch

class MainPage(webapp.RequestHandler):
    def get(self):
        request_token = self.request.get('oauth_token')
        token_secret = self.request.get('token_secret')                
        
        oauth_consumer_key = Constants.API_KEY
        oauth_signature_method = Constants.SIGNATURE_METHOD
        oauth_token = request_token
        key = '%s&%s' % (oAuth.escape(Constants.API_KEY_SECRET), oAuth.escape(token_secret))
        oauth_signature = oAuth.escape(key)
        oauth_timestamp = str(int(time.time()))
        oauth_nonce = oAuth.generate_nonce(8)

        acc_URL = ["http://www.douban.com/service/auth/access_token",
                      "?oauth_consumer_key=",
                      oauth_consumer_key,
                      "&amp;oauth_token=",
                      oauth_token,
                      "&amp;oauth_signature_method=",
                      oauth_signature_method,
                      "&amp;oauth_signature=",
                      oauth_signature,
                      "&amp;oauth_timestamp=",
                      oauth_timestamp,
                      "&amp;oauth_nonce=",
                      oauth_nonce
                     ]
        
        url = ''.join(acc_URL)
        
        result = urlfetch.fetch(url)        
        if result.status_code == 200:            
            xmlStr = result.content            
            url = ''.join(["/douban/miniblog/contact?",xmlStr])                        
        else:            
            url = "/douban/template/timeout.html"
        
        self.redirect(url)
        
def main():
    application = webapp.WSGIApplication([('/douban/token/access', MainPage)],debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()   

